package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService{

    @Autowired
    RoleDao roleDao;

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }


	@Override
	public PageResult findPage(QueryPageBean queryPageBean) {
		//1. 开始分页
		PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
		//2. 根据条件查询（返回值：Page）
		Page<Role> page = roleDao.findByCondition(queryPageBean.getQueryString());
		//创建返回值
		PageResult pageResult = new PageResult(page.getTotal(), page);
		return pageResult;
	}

	@Override
	public void add(Integer[] permissionIds, Role role, Integer[] menuIds) {
		//1. 添加角色（回显主键）
		roleDao.add(role);
		//2. 维护角色和权限的关系
		if(role.getId() != null && permissionIds != null && permissionIds.length > 0){
			for (Integer permissionId : permissionIds) {
				roleDao.set(role.getId(), permissionId);
			}
		}
		if(role.getId() != null && permissionIds != null && permissionIds.length > 0){
			for (Integer menuId : menuIds) {
				roleDao.addMenu(role.getId(), menuId);
			}
		}
	}

	@Override
	public void delRoleById(Integer id) {
		//先判断是否有用户绑定该角色
		int count = roleDao.selWithUser(id);
		if (count>0){
			throw new RuntimeException("该角色已有用户绑定，无法删除");
		}
		//先删除与权限的关联
		roleDao.delAssociationWithPermissionByRoleId(id);
		//再删除角色
		roleDao.delRoleById(id);
	}

	@Override
	public Role findById(Integer id) {
		return roleDao.findByRoleId(id);
	}

	@Override
	public List<Integer> findPermissionIdsByRoleId(Integer id) {
		return roleDao.selPermissionIdsByRoleId(id);
	}

	@Override
	public void editRole(Integer[] permissionIds, Role role, Integer[] menuIds) {
		//先删除与权限的关联
		roleDao.delAssociationWithPermissionByRoleId(role.getId());
		//先删除与菜单的关联
		roleDao.delAssociationWithMenuByRoleId(role.getId());
		//维护角色和权限的关系
		if(role.getId() != null && permissionIds != null && permissionIds.length > 0 ){
			for (Integer permissionId : permissionIds) {
				roleDao.set(role.getId(), permissionId);
			}
		}
		if(role.getId() != null && menuIds != null && menuIds.length > 0){
			for (Integer menuId : menuIds) {
				roleDao.setMenu(role.getId(), menuId);
			}
		}


		//修改角色
		roleDao.updRole(role);
	}

	@Override
	public void addMenu(Role role, Integer menuIds) {
		roleDao.addMenu(role.getId(),menuIds);
	}
}
